/**
 * Copyright 2010 Insigma Technology. 
 * All rights reserved.
 *
 * "LDAPHelper.java is for what: "
 * 
 * Create by Ray at 2012-6-21 下午1:17:07.
 * Ray [email:shilei@insigma.com.cn]
 * 
 * Revision History
 *
 * Date            Programmer                   Notes
 * ---------    ---------------------  -----------------------------------
 * 2012-6-21            Ray                       initial
 **/

package util;

import java.util.HashMap;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

import org.apache.log4j.Logger;

import commonTool.ExecuteResult;

public class LDAPHelper {
	//logger
	private final static Logger log = Logger.getLogger(LDAPHelper.class);

	public static ExecuteResult authenticate(String username, String password) {
        try {
        	Hashtable<String, String> authEnv = new Hashtable<String, String>();
        	String cnName = "";
            //连接到服务器
            authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            authEnv.put(Context.PROVIDER_URL, "ldap://iot.iottech.cc:389/");
            //账户绑定服务器，即认证过程
            authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
            authEnv.put(Context.SECURITY_PRINCIPAL, "cn="+username+",ou=users,ou=staff,dc=insigma,dc=com");
            authEnv.put(Context.SECURITY_CREDENTIALS, password);
            DirContext ctx = new InitialDirContext(authEnv);
            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            controls.setCountLimit(1);
            NamingEnumeration<SearchResult> enumeration = ctx.search(
            		"ou=users,ou=staff,dc=insigma,dc=com", 
            		"cn="+username+"", 
            		controls);
            while(enumeration!=null && enumeration.hasMoreElements())
            {
              SearchResult rs=enumeration.nextElement();
              Attributes attributes = rs.getAttributes();
              cnName = attributes.get("cnName").get().toString();
            }
            return new ExecuteResult(true, null, cnName);
		} catch (Exception e) {
			log.error("authenticate-->", e);
			return new ExecuteResult(false, "登录失败！");
		}
    }
	
	public static void main(String[] args) {
		try {
			boolean result = authenticate("shilei", "lowkey").getIsTrue();
			System.out.println("result-->"+result);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
